﻿using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SocketCore.Common.Message;

public static class JsonHelper
{
    private static readonly JsonSerializerOptions _jsonSerializerOptions = new()
    {
        // PropertyNamingPolicy = JsonNamingPolicy.CamelCase,//驼峰
        ReferenceHandler = ReferenceHandler.IgnoreCycles,//忽略循环引用
        IncludeFields = true,//包含成员字段序列化
        PropertyNameCaseInsensitive = true,//不区分大小写
        AllowTrailingCommas = true,//允许尾随逗号
        ReadCommentHandling = JsonCommentHandling.Skip,//允许注释
        Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,//处理乱码问题
        WriteIndented = true,//是否应使用整齐打印
    };

    public static T? Deserialize<T>(this string value)
    {
        return JsonSerializer.Deserialize<T>(value, _jsonSerializerOptions);
    }

    public static string Serialize<T>(this T? value)
    {
        return JsonSerializer.Serialize(value, _jsonSerializerOptions);
    }
}